package com.springcloud.sc.ucpv5.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springcloud.sc.ucp.v5.api.entity.JobUcpSchedule;
import com.springcloud.sc.ucpv5.client.commondata.MyGroup;
import com.springcloud.sc.ucpv5.client.commondata.MyUser;
import com.springcloud.sc.ucpv5.client.commondata.MyUserInfoOtherData;
import com.springcloud.sc.ucpv5.client.commondata.data.UserInfo;
import com.springcloud.sc.ucpv5.client.module.datamanager.BaseDataManager;
import com.springcloud.sc.ucpv5.mapper.JobUcpScheduleMapper;
import com.springcloud.sc.ucpv5.service.JobUcpScheduleService;
import com.springcloud.sc.ucpv5.tree.GroupNodeVoip;
import com.springcloud.sc.ucpv5.tree.UserNode;
import com.springcloud.sc.ucpv5.tree.VoiceAuthorityNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class JobUcpScheduleServiceImpl extends ServiceImpl<JobUcpScheduleMapper, JobUcpSchedule> implements JobUcpScheduleService {

    @Autowired
    private JobUcpScheduleMapper jobUcpScheduleMapper;


    @Override
    public boolean saveJobUcpSchedule(String id, String json , String jobName) {
        JobUcpSchedule jobUcpSchedule = new JobUcpSchedule();
        jobUcpSchedule.setTaskId( id );
        jobUcpSchedule.setExecutionSource( json ) ;
        jobUcpSchedule.setIsSuccess(0);
        jobUcpSchedule.setStartTime(new Date());
        jobUcpSchedule.setJobName( jobName );
        Integer integer = jobUcpScheduleMapper.insert( jobUcpSchedule );
        return SqlHelper.retBool(integer);
    }

    public boolean deleteEntityByUserInfo(UserInfo userInfo , String jobName){
        Map map = new HashMap();
        List list = new ArrayList();
        map.put("number" , userInfo.getUserTelno() );
        list.add(map);
        Object json = JSONArray.toJSON(  list );
        return this.saveJobUcpSchedule( userInfo.getUserTelno() , json.toString() , jobName );
    }

    public boolean saveEntityByUserInfo(UserInfo userInfo , String jobName){
        List<UserNode> userList = new ArrayList<>();
        UserNode userNode = new UserNode();
        userNode.setName( userInfo.getUserName() );
        userNode.setNumber( userInfo.getUserTelno() );
        userNode.setPassword( userInfo.getPassword() );
        int userType = userInfo.getUserType();
        int userTypeData = userType & 0x000000FF;
        int tmp = (userType >> 10) & 0x0000000F;
        userType = userTypeData * 10 + tmp;

        //用户类型为1，表示是手机号码，则为外网用户
        if(userType == 1 || userType == 2){
            userNode.setUserType( "1" );
        }else{
            userNode.setUserType( "0" );
        }

        try{
            try {
                // 从缓存额外信息的iconname字段中解析出来该用户可发起语音发布权限的组列表
                MyUserInfoOtherData otherInfo = JSON.parseObject(userInfo.UserIconName, MyUserInfoOtherData.class);
                if(otherInfo.voiceAuthorityGroupList != null && otherInfo.voiceAuthorityGroupList.size() > 0){
                    // 如果组列表不为空, 则具有语音发布权限
                    userNode.setVoiceAuthority("1");
                    List<VoiceAuthorityNode> voiceAuthorityNodeList = new ArrayList<>();
                    for(String groupNumber : otherInfo.voiceAuthorityGroupList){
                        try{
                            MyGroup group_tmp = BaseDataManager.getInstance().groupGet(groupNumber);
                            if(group_tmp == null){
                                System.out.println("JobUcpScheduleServiceImpl 用户修改通知, 组不存在:" + groupNumber);
                            }
                            else if(!group_tmp.isYingJiZu()){
                                System.out.println("JobUcpScheduleServiceImpl 用户修改通知, 组不是应急组:" + groupNumber);
                            }
                            else if(group_tmp.isYingJiZu()){
                                VoiceAuthorityNode voiceAuthorityNode = new VoiceAuthorityNode();
                                voiceAuthorityNode.setNumber(groupNumber);
                                voiceAuthorityNodeList.add( voiceAuthorityNode );
                            }
                        }catch(Exception e){
                            e.printStackTrace();
                        }
                    }
                    userNode.setVoiceAuthorityGroupList( voiceAuthorityNodeList );
                }
                else{
                    // 可发布的组为空, 则不具有发布权限
                    userNode.setVoiceAuthority("0");
                }

                //outcid 属性
                try{
                    if(otherInfo.outcid != null && !otherInfo.outcid.equals("")){
                        userNode.setOutcid(otherInfo.outcid);
                    }
                }catch (Exception e){
                    //e.printStackTrace();
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        userList.add( userNode );
        Object json = JSONArray.toJSON(  userList );
        return this.saveJobUcpSchedule( userInfo.getUserTelno() , json.toString() , jobName );

    }

    public boolean saveEntityByMyGroup(MyGroup myGroup , String jobName){
        try {
            List<GroupNodeVoip> groupNodeVoipList = new ArrayList<GroupNodeVoip>();
            GroupNodeVoip groupNodeVoip = new GroupNodeVoip();
            groupNodeVoip.setNumber( myGroup.getIdlData().getGroupTelno() );
            groupNodeVoip.setName( myGroup.getIdlData().getGroupName() );
            groupNodeVoip.setOperType(1);

            // wsy 20190604 处理组的编号下发
            if(myGroup.getIdlData().getKeep1() != null && !myGroup.getIdlData().getKeep1().equals("")){
                groupNodeVoip.setSign(myGroup.getIdlData().getKeep1());
            }

            List<UserNode> userList = new ArrayList<>();
            ArrayList<MyUser> myUsersList = myGroup.getListModel().getUserList();
            if(!myUsersList.isEmpty()){
                myUsersList.forEach(myUser -> {
                    UserNode userNode = new UserNode();
                    userNode.setName( myUser.getIdlData().getUserName() );
                    userNode.setNumber( myUser.getIdlData().getUserTelno() );
                    userNode.setPassword( myUser.getIdlData().getPassword() );
                    int userType = myUser.getIdlData().getUserType();
                    int userTypeData = userType & 0x000000FF;
                    int tmp = (userType >> 10) & 0x0000000F;
                    userType = userTypeData * 10 + tmp;

                    //用户类型为1，表示是手机号码，则为外网用户
                    if(userType == 1 || userType == 2){
                        userNode.setUserType( "1" );
                    }else{
                        userNode.setUserType( "0" );
                    }

                    try{
                        try {
                            // 从缓存额外信息的iconname字段中解析出来该用户可发起语音发布权限的组列表
                            MyUserInfoOtherData otherInfo = myUser.getUserInfoData().otherInfo;
                            if(otherInfo.voiceAuthorityGroupList != null && otherInfo.voiceAuthorityGroupList.size() > 0){
                                // 如果组列表不为空, 则具有语音发布权限
                                userNode.setVoiceAuthority("1");
                                List<VoiceAuthorityNode> voiceAuthorityNodeList = new ArrayList<>();
                                for(String groupNumber : otherInfo.voiceAuthorityGroupList){
                                    try{
                                        MyGroup group_tmp = BaseDataManager.getInstance().groupGet(groupNumber);
                                        if(group_tmp == null){
                                            System.out.println("JobUcpScheduleServiceImpl 用户修改通知, 组不存在:" + groupNumber);
                                        }
                                        else if(!group_tmp.isYingJiZu()){
                                            System.out.println("JobUcpScheduleServiceImpl 用户修改通知, 组不是应急组:" + groupNumber);
                                        }
                                        else if(group_tmp.isYingJiZu()){
                                            VoiceAuthorityNode voiceAuthorityNode = new VoiceAuthorityNode();
                                            voiceAuthorityNode.setNumber(groupNumber);
                                            voiceAuthorityNodeList.add( voiceAuthorityNode );
                                        }
                                    }catch(Exception e){
                                        e.printStackTrace();
                                    }
                                }
                                userNode.setVoiceAuthorityGroupList( voiceAuthorityNodeList );
                            }
                            else{
                                // 可发布的组为空, 则不具有发布权限
                                userNode.setVoiceAuthority("0");
                            }

                            //outcid 属性
                            try{
                                if(otherInfo.outcid != null && !otherInfo.outcid.equals("")){
                                    userNode.setOutcid(otherInfo.outcid);
                                }
                            }catch (Exception e){
                                //e.printStackTrace();
                            }
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    userList.add( userNode );
                });
            }
            groupNodeVoip.setUserList( userList );

            Object json = JSONArray.toJSON(  groupNodeVoip );

            return this.saveJobUcpSchedule( myGroup.getIdlData().getGroupTelno() , json.toString() , jobName );
        } catch (Exception e) {
            e.printStackTrace();
        }
       return false;
    }

    public List<JobUcpSchedule> getListByUnsent(){
        return jobUcpScheduleMapper.getListByUnsent();
    }

    public Integer updateEntity(JobUcpSchedule entity){
        return jobUcpScheduleMapper.updateById( entity );

    }

    // wsy 20190609 z=增加操作任务下发
    public boolean saveEntityByOperData(String data, String jobName){
        try {
            return this.saveJobUcpSchedule("operdata", data, jobName );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
